<template>
  <view class="comments-page">
    <!-- 评论统计 -->
    <view class="comment-stats" @tap="showSortOptions">
      <text class="stats-text">共{{ totalComments }}条评论</text>
      <text class="sort-text">{{ currentSortBy === 'create_time' ? '按最新' : '按最热' }}</text>
      <u-icon name="arrow-down" size="12" color="#999" />
    </view>

    <!-- 评论输入区 -->
    <view class="comment-input-section">
      <view class="input-container">
        <image
          class="user-avatar"
          :src="
            currentUserInfo?.headerImg || currentUserInfo?.avatar || currentUserInfo?.profileImage
          "
          mode="aspectFill"
        />
        <view class="input-box" @tap="showCommentInput">
          <text class="placeholder">{{
            replyToComment ? `回复 ${replyToComment.publisher_name}` : '有话要说，快来评论'
          }}</text>
        </view>
        <view class="action-buttons">
          <u-icon name="heart" size="20" color="#666" @click="handleLike" />
          <u-icon name="star" size="20" color="#666" @click="handleCollect" />
          <u-icon name="share" size="20" color="#666" @click="handleShare" />
        </view>
      </view>
    </view>

    <!-- 评论列表 -->
    <scroll-view
      class="comment-list"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
    >
      <view v-for="comment in commentList" :key="comment.comment_id" class="comment-item">
        <!-- 一级评论 -->
        <view class="comment-content">
          <image
            class="avatar"
            :src="comment.publisher_image || '/static/images/default-avatar.png'"
            mode="aspectFill"
          />
          <view class="content-right">
            <view class="user-info">
              <text class="username">{{ comment.publisher_name }}</text>
              <text class="time">{{ formatTime(comment.create_time) }}</text>
            </view>
            <!-- 编辑状态 -->
            <view v-if="comment.isEditing" class="edit-comment">
              <textarea
                v-model="comment.editText"
                class="edit-textarea"
                auto-height
                maxlength="500"
              />
              <view class="edit-actions">
                <text class="cancel-edit" @tap="cancelEditComment(comment)">取消</text>
                <text class="save-edit" @tap="saveEditComment(comment)">保存</text>
              </view>
            </view>
            <!-- 普通显示状态 -->
            <text v-else class="comment-text">{{ comment.comment_text }}</text>

            <!-- 操作按钮 -->
            <view class="comment-actions">
              <view class="action-item">
                <u-icon name="thumb-up" color="#999" size="16" />
                <text class="action-text">{{ comment.likes || '' }}</text>
              </view>
              <view class="action-item">
                <u-icon name="thumb-down" color="#999" size="16" />
                <text class="action-text">{{ comment.dislikes || '' }}</text>
              </view>
              <view class="action-item">
                <u-icon name="star" color="#999" size="16" />
                <text class="action-text">{{ comment.marks || '' }}</text>
              </view>
              <view class="action-item" @tap="showReplyInput(comment)">
                <u-icon name="chat" color="#999" size="16" />
                <text class="action-text">回复</text>
              </view>
              <view
                v-if="comment.publisher_id === parseInt(currentUserId)"
                class="action-item"
                @tap="startEditComment(comment)"
              >
                <u-icon name="edit-pen" color="#999" size="16" />
                <text class="action-text">编辑</text>
              </view>
            </view>

            <!-- 二级评论 -->
            <view v-if="comment.child_comments > 0" class="child-comments">
              <view
                v-if="!comment.childList?.length"
                class="load-replies"
                @tap="loadChildComments(comment)"
              >
                <text class="load-text">查看{{ comment.child_comments }}条回复</text>
                <u-icon name="arrow-down" size="12" color="#999" />
              </view>
              <view v-else>
                <!-- 收起按钮 -->
                <view class="collapse-replies" @tap="collapseChildComments(comment)">
                  <text class="collapse-text">收起回复</text>
                  <u-icon name="arrow-up" size="12" color="#999" />
                </view>
                <view
                  v-for="childComment in comment.childList"
                  :key="childComment.comment_id"
                  class="child-comment"
                >
                  <image
                    class="child-avatar"
                    :src="childComment.publisher_image || '/static/images/default-avatar.png'"
                    mode="aspectFill"
                  />
                  <view class="child-content">
                    <view class="child-user-info">
                      <text class="child-username">{{ childComment.publisher_name }}</text>
                      <text class="child-time">{{ formatTime(childComment.create_time) }}</text>
                    </view>
                    <!-- 子评论编辑状态 -->
                    <view v-if="childComment.isEditing" class="edit-comment">
                      <textarea
                        v-model="childComment.editText"
                        class="edit-textarea"
                        auto-height
                        maxlength="500"
                      />
                      <view class="edit-actions">
                        <text class="cancel-edit" @tap="cancelEditComment(childComment)">取消</text>
                        <text class="save-edit" @tap="saveEditComment(childComment)">保存</text>
                      </view>
                    </view>
                    <!-- 子评论普通显示状态 -->
                    <text v-else class="child-comment-text">{{ childComment.comment_text }}</text>

                    <!-- 子评论操作 -->
                    <view class="child-actions">
                      <view class="action-item">
                        <u-icon name="thumb-up" color="#999" size="14" />
                        <text class="action-text">{{ childComment.likes || '' }}</text>
                      </view>
                      <view class="action-item">
                        <u-icon name="star" color="#999" size="14" />
                        <text class="action-text">{{ childComment.marks || '' }}</text>
                      </view>
                      <view class="action-item" @tap="showReplyInput(childComment, comment)">
                        <u-icon name="chat" color="#999" size="14" />
                        <text class="action-text">回复</text>
                      </view>
                      <view
                        v-if="childComment.publisher_id === parseInt(currentUserId)"
                        class="action-item"
                        @tap="startEditComment(childComment)"
                      >
                        <u-icon name="edit-pen" color="#999" size="14" />
                        <text class="action-text">编辑</text>
                      </view>
                    </view>
                  </view>
                </view>
                <view
                  v-if="comment.childList.length < comment.child_comments"
                  class="load-more-replies"
                  @tap="loadMoreChildComments"
                >
                  <text class="load-text">查看更多回复</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more">
        <u-loading-icon show />
        <text class="load-text">加载中...</text>
      </view>
      <view v-else-if="commentList.length > 0" class="no-more">
        <text class="no-more-text">没有更多评论了</text>
      </view>
    </scroll-view>

    <!-- 评论输入弹窗 -->
    <u-popup v-model:show="showInput" mode="bottom" :border-radius="20">
      <view class="comment-input-popup">
        <view class="input-header">
          <text class="input-title">{{
            replyToComment ? `回复 ${replyToComment.publisher_name}` : '发表评论'
          }}</text>
          <view class="header-actions">
            <text class="cancel-btn" @tap="hideCommentInput">取消</text>
            <text class="send-btn" :class="{ disabled: !commentText.trim() }" @tap="submitComment"
              >发送</text
            >
          </view>
        </view>
        <view class="input-content">
          <textarea
            v-model="commentText"
            class="comment-textarea"
            placeholder="说点什么..."
            :focus="showInput"
            auto-height
            maxlength="500"
          />
          <view class="char-count">{{ commentText.length }}/500</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import { CommentService } from '@/services';
  import type { Comment, GetCommentsParams, PublishCommentParams } from '@/types';
  import dayjs from 'dayjs';
  import relativeTime from 'dayjs/plugin/relativeTime';
  import 'dayjs/locale/zh-cn';

  dayjs.extend(relativeTime);
  dayjs.locale('zh-cn');

  // 页面参数
  interface PageParams {
    content_id: string;
    user_id: string;
  }

  // 用户信息类型定义
  interface UserInfo {
    ID?: number; // 大写ID字段
    id?: number; // 小写id字段
    headerImg?: string; // me页面使用的头像字段
    avatar?: string;
    profileImage?: string;
    nickname?: string;
    nickName?: string;
    [key: string]: any;
  }

  // 扩展评论类型，添加前端状态
  interface ExtendedComment extends Comment {
    childList?: ExtendedComment[];
    isEditing?: boolean;
    editText?: string;
  }

  // 响应式数据
  const commentList = ref<ExtendedComment[]>([]);
  const refreshing = ref(false);
  const hasMore = ref(true);
  const totalComments = ref(0);
  const showInput = ref(false);
  const commentText = ref('');
  const replyToComment = ref<ExtendedComment | null>(null);
  const parentCommentForReply = ref<ExtendedComment | null>(null);
  const currentUserInfo = ref<UserInfo | null>(null);
  const currentSortBy = ref('create_time'); // 当前排序方式，默认按最新

  // 页面参数
  const pageParams = ref<PageParams>({
    content_id: '',
    user_id: '',
  });

  // 计算属性
  const currentUserId = computed(() => {
    const userInfo = uni.getStorageSync('userInfo');

    // 支持多种ID字段格式：ID（大写）、id（小写）
    const userId = userInfo?.ID || userInfo?.id;
    if (userInfo && userId) {
      return userId.toString();
    }

    if (pageParams.value.user_id) {
      return pageParams.value.user_id;
    }

    console.warn('未能获取到有效的用户ID');
    return '0'; // 返回默认值而不是空字符串
  });

  // 页面加载
  onLoad((options: any) => {
    // 处理content_id参数
    if (options && options.content_id) {
      pageParams.value.content_id = options.content_id;
    } else {
      console.warn('未传递content_id参数');
      // 临时测试：使用一个有数据的content_id
      pageParams.value.content_id = '1'; // 确认使用content_id=1
      uni.showToast({
        title: '临时测试模式',
        icon: 'none',
      });
    }

    // 处理user_id参数（可选）
    if (options && options.user_id) {
      pageParams.value.user_id = options.user_id;
    }

    // 加载用户信息
    loadCurrentUserInfo();
  });

  onMounted(() => {
    // 确保有content_id后再加载评论数据
    if (pageParams.value.content_id) {
      loadComments();
    } else {
      console.error('缺少内容ID参数');
      uni.showToast({
        title: '缺少内容ID参数',
        icon: 'none',
      });
    }
  });

  // 加载当前用户信息
  const loadCurrentUserInfo = () => {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      currentUserInfo.value = userInfo;
    } else {
      console.warn('未找到用户信息，请先登录');
    }
  };

  // 格式化时间
  const formatTime = (timestamp: number) => {
    try {
      // 假设后端返回的是秒级时间戳
      return dayjs.unix(timestamp).fromNow();
    } catch {
      return '刚刚';
    }
  };

  // 检查用户登录状态
  const checkUserLogin = (): boolean => {
    const userInfo = uni.getStorageSync('userInfo');
    const userId = userInfo?.ID || userInfo?.id;

    if (!userInfo || !userId) {
      uni.showToast({
        title: '请先登录',
        icon: 'none',
      });
      return false;
    }
    return true;
  };

  // 加载评论列表
  const loadComments = async (isRefresh = false) => {
    try {
      // 检查用户登录状态
      if (!checkUserLogin()) {
        return;
      }

      if (isRefresh) {
        refreshing.value = true;
      }

      const contentId = parseInt(pageParams.value.content_id);

      if (isNaN(contentId) || contentId <= 0) {
        uni.showToast({
          title: '内容ID无效',
          icon: 'none',
        });
        return;
      }

      const params: GetCommentsParams = {
        content_id: contentId,
        parent_comment_id: 0, // 0表示获取一级评论
        order_by: currentSortBy.value,
        page_size: 20,
        page_num: 1,
      };

      const data = await CommentService.getComments(params);

      // 正确提取评论数据：CommentService 已处理响应，直接返回数据
      const dataArray = data.comments || [];

      if (isRefresh) {
        commentList.value = dataArray;
      } else {
        commentList.value.push(...dataArray);
      }
      totalComments.value = data.total || dataArray.length;

      // 检查是否还有更多数据
      hasMore.value = dataArray.length >= 20; // 假设每页20条
    } catch (error) {
      console.error('获取评论失败:', error);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none',
      });
    } finally {
      refreshing.value = false;
    }
  };

  // 加载子评论
  const loadChildComments = async (parentComment: ExtendedComment) => {
    try {
      const params: GetCommentsParams = {
        content_id: parseInt(pageParams.value.content_id),
        parent_comment_id: parentComment.comment_id,
        // 子评论也使用默认排序
      };

      const data = await CommentService.getComments(params);

      // 子评论也需要正确提取：CommentService 已处理响应，直接返回数据
      parentComment.childList = data.comments || [];
    } catch (error) {
      console.error('获取子评论失败:', error);
      uni.showToast({
        title: '获取回复失败',
        icon: 'none',
      });
    }
  };

  // 加载更多子评论
  const loadMoreChildComments = async () => {
    // 这里可以实现分页加载更多子评论的逻辑
    console.log('加载更多子评论功能待实现');
  };

  // 收起子评论
  const collapseChildComments = (parentComment: ExtendedComment) => {
    parentComment.childList = [];
  };

  // 显示排序选项
  const showSortOptions = () => {
    const sortOptions = ['按最新', '按最热'];

    uni.showActionSheet({
      itemList: sortOptions,
      success: function (res) {
        const newSortBy = res.tapIndex === 0 ? 'create_time' : 'likes';
        if (newSortBy !== currentSortBy.value) {
          currentSortBy.value = newSortBy;
          // 重新加载评论
          loadComments(true);
        }
      },
    });
  };

  // 下拉刷新
  const onRefresh = () => {
    loadComments(true);
  };

  // 上拉加载更多
  const onLoadMore = () => {
    if (hasMore.value) {
      loadComments();
    }
  };

  // 显示评论输入框
  const showCommentInput = () => {
    replyToComment.value = null;
    parentCommentForReply.value = null;
    showInput.value = true;
  };

  // 显示回复输入框
  const showReplyInput = (comment: ExtendedComment, parentComment?: ExtendedComment) => {
    replyToComment.value = comment;
    parentCommentForReply.value = parentComment || comment;
    showInput.value = true;
  };

  // 隐藏评论输入框
  const hideCommentInput = () => {
    showInput.value = false;
    commentText.value = '';
    replyToComment.value = null;
    parentCommentForReply.value = null;
  };

  // 提交评论
  const submitComment = async () => {
    if (!commentText.value.trim()) {
      return;
    }

    // 检查用户登录状态
    if (!checkUserLogin()) {
      return;
    }

    try {
      const userId = parseInt(currentUserId.value);
      const contentId = parseInt(pageParams.value.content_id);

      if (isNaN(userId) || userId <= 0) {
        uni.showToast({
          title: '用户ID无效，请重新登录',
          icon: 'none',
        });
        return;
      }

      const params: PublishCommentParams = {
        content_id: contentId,
        publisher_id: userId,
        parent_comment_id: replyToComment.value ? parentCommentForReply.value!.comment_id : 0,
        show_parent_comment_id: replyToComment.value
          ? parentCommentForReply.value!.comment_id
          : undefined,
        comment_text: commentText.value.trim(),
      };

      await CommentService.publishComment(params);

      // 发布成功，重新加载评论
      uni.showToast({
        title: '评论成功',
        icon: 'success',
      });

      hideCommentInput();
      // 刷新评论列表
      loadComments(true);
    } catch (error) {
      console.error('发布评论失败:', error);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none',
      });
    }
  };

  // 开始编辑评论
  const startEditComment = (comment: ExtendedComment) => {
    comment.isEditing = true;
    comment.editText = comment.comment_text;
  };

  // 取消编辑评论
  const cancelEditComment = (comment: ExtendedComment) => {
    comment.isEditing = false;
    comment.editText = '';
  };

  // 保存编辑评论
  const saveEditComment = async (comment: ExtendedComment) => {
    if (!comment.editText?.trim()) {
      uni.showToast({
        title: '评论内容不能为空',
        icon: 'none',
      });
      return;
    }

    try {
      await CommentService.updateComment(comment.comment_id, comment.editText.trim());

      // 更新成功，更新本地数据
      comment.comment_text = comment.editText.trim();
      comment.isEditing = false;
      comment.editText = '';

      uni.showToast({
        title: '修改成功',
        icon: 'success',
      });
    } catch (error) {
      console.error('修改评论失败:', error);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none',
      });
    }
  };

  // 处理主要操作按钮（顶部的点赞、收藏、分享按钮，这些可能是针对内容而不是评论的）
  const handleLike = () => {
    uni.showToast({
      title: '内容点赞功能待开发',
      icon: 'none',
    });
  };

  const handleCollect = () => {
    uni.showToast({
      title: '内容收藏功能待开发',
      icon: 'none',
    });
  };

  const handleShare = () => {
    uni.showToast({
      title: '分享功能待开发',
      icon: 'none',
    });
  };
</script>

<style lang="scss" scoped>
  .comments-page {
    min-height: 100vh;
    background-color: #f8f8f8;
    display: flex;
    flex-direction: column;
  }

  .comment-input-section {
    background: white;
    padding: 24rpx;
    border-bottom: 1rpx solid #eee;

    .input-container {
      display: flex;
      align-items: center;
      gap: 20rpx;

      .user-avatar {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        background: #f0f0f0;
      }

      .input-box {
        flex: 1;
        background: #f5f5f5;
        border-radius: 40rpx;
        padding: 16rpx 24rpx;

        .placeholder {
          color: #999;
          font-size: 28rpx;
        }
      }

      .action-buttons {
        display: flex;
        gap: 32rpx;
      }
    }
  }

  .comment-stats {
    background: white;
    padding: 24rpx;
    border-bottom: 1rpx solid #f8f8f8;
    display: flex;
    align-items: center;
    gap: 12rpx;
    cursor: pointer;

    .stats-text {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }

    .sort-text {
      font-size: 26rpx;
      color: #4a90e2;
    }
  }

  .comment-list {
    flex: 1;
    background: white;
  }

  .comment-item {
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }

  .comment-content {
    padding: 24rpx;
    display: flex;
    gap: 20rpx;

    .avatar {
      width: 72rpx;
      height: 72rpx;
      border-radius: 50%;
      border: 1rpx solid #f0f0f0;
      flex-shrink: 0;
    }

    .content-right {
      flex: 1;

      .user-info {
        display: flex;
        align-items: center;
        gap: 20rpx;
        margin-bottom: 12rpx;

        .username {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }

      .comment-text {
        font-size: 30rpx;
        color: #333;
        line-height: 1.5;
        margin-bottom: 20rpx;
        display: block;
      }

      .comment-actions {
        display: flex;
        gap: 40rpx;

        .action-item {
          display: flex;
          align-items: center;
          gap: 8rpx;

          .action-text {
            font-size: 24rpx;
            color: #999;

            &.liked {
              color: #ff3040;
            }

            &.marked {
              color: #ffad33;
            }
          }
        }
      }
    }
  }

  .child-comments {
    margin-top: 20rpx;
    padding-left: 24rpx;

    .load-replies {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 16rpx 0;

      .load-text {
        font-size: 26rpx;
        color: #4a90e2;
      }
    }

    .collapse-replies {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 16rpx 0;

      .collapse-text {
        font-size: 26rpx;
        color: #4a90e2;
      }
    }

    .child-comment {
      display: flex;
      gap: 16rpx;
      padding: 16rpx 0;

      .child-avatar {
        width: 56rpx;
        height: 56rpx;
        border-radius: 50%;
        border: 1rpx solid #f0f0f0;
        flex-shrink: 0;
      }

      .child-content {
        flex: 1;

        .child-user-info {
          display: flex;
          align-items: center;
          gap: 16rpx;
          margin-bottom: 8rpx;

          .child-username {
            font-size: 26rpx;
            color: #333;
            font-weight: 500;
          }

          .child-time {
            font-size: 22rpx;
            color: #999;
          }
        }

        .child-comment-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.5;
          margin-bottom: 16rpx;
          display: block;
        }

        .child-actions {
          display: flex;
          gap: 32rpx;

          .action-item {
            display: flex;
            align-items: center;
            gap: 6rpx;

            .action-text {
              font-size: 22rpx;
              color: #999;

              &.liked {
                color: #ff3040;
              }

              &.marked {
                color: #ffad33;
              }
            }
          }
        }
      }
    }

    .load-more-replies {
      padding: 16rpx 0;

      .load-text {
        font-size: 26rpx;
        color: #4a90e2;
      }
    }
  }

  .load-more,
  .no-more {
    padding: 40rpx;
    text-align: center;

    .load-text,
    .no-more-text {
      font-size: 26rpx;
      color: #999;
      margin-left: 16rpx;
    }
  }

  .comment-input-popup {
    background: white;

    .input-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx 24rpx 0;
      border-bottom: 1rpx solid #eee;

      .input-title {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
      }

      .header-actions {
        display: flex;
        gap: 32rpx;

        .cancel-btn {
          font-size: 28rpx;
          color: #999;
        }

        .send-btn {
          font-size: 28rpx;
          color: #4a90e2;

          &.disabled {
            color: #ccc;
          }
        }
      }
    }

    .input-content {
      padding: 24rpx;

      .comment-textarea {
        width: 100%;
        min-height: 200rpx;
        font-size: 30rpx;
        line-height: 1.5;
        resize: none;
        border: none;
        outline: none;
      }

      .char-count {
        text-align: right;
        font-size: 24rpx;
        color: #999;
        margin-top: 16rpx;
      }
    }
  }

  .edit-comment {
    margin: 16rpx 0;

    .edit-textarea {
      width: 100%;
      min-height: 120rpx;
      padding: 16rpx;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;
      font-size: 28rpx;
      line-height: 1.5;
      background: #fff;
      resize: none;
      outline: none;
    }

    .edit-actions {
      display: flex;
      justify-content: flex-end;
      gap: 24rpx;
      margin-top: 16rpx;

      .cancel-edit {
        font-size: 26rpx;
        color: #999;
        padding: 8rpx 16rpx;
      }

      .save-edit {
        font-size: 26rpx;
        color: #4a90e2;
        padding: 8rpx 16rpx;
      }
    }
  }
</style>
